import type { UserConfig, ConfigEnv } from 'vite'
import { loadEnv } from 'vite'
import { resolve } from 'path'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import Components from 'unplugin-vue-components/vite'
import NutUIResolver from '@nutui/auto-import-resolver'
import UnoCSS from 'unocss/vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

// 主要用于alias文件路径别名
function pathResolve(dir: string) {
  return resolve(__dirname, '.', dir)
}

const timeStamp = new Date().getTime()

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd()
  const env = loadEnv(mode, root)
  return {
    base: env.VITE_PUBLIC_PATH,
    root,
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "@nutui/nutui/dist/styles/variables-jdt.scss";`,
        },
      }
    },
    plugins: [
      vue(),
      vueJsx(),
      Components({
        resolvers: [NutUIResolver()],
        dts: false
      }),
      UnoCSS(),
      // Svg
      createSvgIconsPlugin({
        // 图标文件夹
        iconDirs: [pathResolve('src/assets/svgs')],
      }),
    ],
    resolve: {
      alias: [
        // @/xxxx => src/xxxx 为啥匹配 @/ 因为有些第三方包是以 @ 开头的
        {
          find: /@\//,
          replacement: pathResolve('src') + '/',
        },
        // #/xxxx => types/xxxx
        {
          find: /#\//,
          replacement: pathResolve('types') + '/',
        },
      ],
    },
    build: {
      rollupOptions: {
        output: {
          assetFileNames: `assets/[name]-${timeStamp}[extname]`
        }
      }
    },
    // 本地运行配置，及反向代理配置
    server: {
      port: 3000,
      host: '0.0.0.0',
      // 是否开启 https
      cors: true, // 默认启用并允许任何源
      open: false, // 在服务器启动时自动在浏览器中打开应用程序
      proxy: {
        '/dev/api': {
          target: 'http://xxx:8080/', // dev
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '/'),
        },
      },
    }
  }
}
